import { t } from 'i18next'
import { CheckBox, CheckBoxGroup, InnerInputRef, Input, Message, Modal, Radio, Select } from '@kedacom/react-next'
import { CheckBoxWrap, PhoneModalWrap, RadioWrap, StyledRejectMeetingWrap, Wrap, WrapFooter } from './style'
import AuthenticationCheck from '@/components/AuthenticationCheck'
import { CommonCard } from './components/common'
import { useEffect, useRef, useState } from 'react'
import { Button } from '@kedacom/react-next'
import { MeetingCardProps, MeetingEntity, SelectType } from '../interface'
import useCheckAuthentication from '@/components/AuthenticationCheck/useCheckAuthentication'
import shallow from 'zustand/shallow'
import { useStore as useMeetingScheduleStore } from '../store'
import {
	fetchDeleteMeetingByReason,
	fetchDeleteRegularMeetingByReason,
	fetchRegularMeeting,
	fetchStartMeetingNow,
} from '@/api/meetingList'
import jumpPage from '@/utils/jumpPage'
import useCreateConfs from '@/hooks/useCreateConfs'
import Alert from '@/components/Alert'
import dayjs from '@/plugins/dayjs'
import { fetchSetCookie } from '@/api/global'
import { MEETING_JUMP_URL } from '@/utils/constant'
import { useGlobalStore } from '@/store/global'
import { regexEnum } from '@/utils'

type DateIndoEntity = Array<{
	value: number
	label: string
	day: string
	meeting_moid: string
	height: number
}>

export function AppointmentCard(props: MeetingCardProps) {
	const { run } = useCreateConfs()
	const {
		run: checkAuthentication,
		open: isAuthenticationOpen,
		setOpen: setIsAuthenticationOpen,
		successFn,
	} = useCheckAuthentication()
	const {
		isValidLink,
		update,
		failure,
		attending_info,
		AjaxFetchAppointmentMeetingList,
		AjaxFetchNotParticipateMeetingList,
	} = useMeetingScheduleStore(
		(state) => ({
			update: state.update,
			failure: state.failure,
			isValidLink: state.isValidLink,
			actionParticipate: state.actionParticipate,
			attending_info: state.attending_info,
			AjaxFetchAppointmentMeetingList: state.AjaxFetchAppointmentMeetingList,
			AjaxFetchNotParticipateMeetingList: state.AjaxFetchNotParticipateMeetingList,
		}),
		shallow
	)
	/**取消例会的弹框*/
	const [is_show_cancel_regular_meeting, setIsShowRegularMeeting] = useState(false)
	/**取消例会的弹框*/
	const [is_show_participate_modal, setIsShowParticipateModal] = useState(false)
	const [participate_type_radio, setParticipateTypeRadio] = useState(2)
	const [phone, setPhone] = useState('')
	const [is_show_phone_participate_modal, setIsShowPhoneParticipateModal] = useState(false)
	const [date_info, setDateInfo] = useState<DateIndoEntity>([])
	/**参会方式的下拉选择项 */
	const [value, setValue] = useState<string>('1')
	const [attendingMsg, setAttendingMsg] = useState<string>('')
	/**取消会议弹框*/
	const [checkboxCheckValueList, setCheckboxCheckValueList] = useState<Array<number>>([]) /**设置多选全选的列表*/
	const [init_select_checkbox_value, setInitSelectCheckboxValue] =
		useState('') /**当打开取消例会的弹框会默认选中一个值,这个值就当前会议 */
	const [allValue, setAllValue] = useState(false)
	const [is_show_cancel_modal, setIsShowCancelModal] = useState(false) // 取消会议弹框显示
	const [cancel_value, setCancelValue] = useState(1) // 取消会议原因弹框(时间冲突 其他)
	const [cancel_resason, setCancelReason] = useState('') // 取消会议原因弹框(时间冲突 其他) 原因
	/**不参加会议弹框*/
	const [is_show_not_participate_modal, setIsShowNotParticipateModal] = useState(false) // 弹框显示
	const [not_participate_value, setNotParticipateValue] = useState(1) // 不参加会议选择按钮值
	const [not_participate_resason, setNotParticipateReason] = useState('') // 不参加会议的原因
	const SWITCH = useGlobalStore((state) => state.SWITCH)
	const ref = useRef<InnerInputRef>(null)
	/**取消会议的原因*/
	const cancelResasonRef = useRef<InnerInputRef>(null)
	/**不参加会议原因*/
	const notParticipateResasonRef = useRef<InnerInputRef>(null)
	useEffect(() => {
		const { video, current_user_attendee } = props.entity
		const { is_participated, participated_type } = current_user_attendee
		if (current_user_attendee) {
			if (!is_participated) {
				setAttendingMsg(t('不参加'))
			} else {
				if (participated_type === 2) {
					setValue('2')
					setAttendingMsg('')
				} else if (participated_type === 3) {
					setValue('3')
					setAttendingMsg('')
				} else if (participated_type === 1) {
					if (!video) {
						/**此种情况不存在  现在都是视频会议*/
						setAttendingMsg(t('去会议室参加'))
					} else {
						setAttendingMsg('')
						setValue('1')
					}
				} else {
					setAttendingMsg(t('不参加'))
				}
			}
		} else {
			setAttendingMsg('')
		}
	}, [props])
	/**取消例会时间多选确认前重置参数*/
	const actionCancelMeetingModalTimeConfirmRest = () => {
		setIsShowRegularMeeting(false) /**选择取消例会时间弹框关闭 */
		setCancelReason('')
	}
	/**获取入会方式*/
	const getMembershipMethod = (meeting: MeetingEntity): SelectType => {
		const meeting_type = meeting.meeting_type ?? 2
		if (meeting_type === 2) {
			return [
				{
					value: '2',
					label: t('通过个人客户端参加'),
				},
				{
					value: '1',
					label: t('去会议室参加'),
				},
			]
		} else {
			return [
				{
					value: '2',
					label: t('通过个人客户端参加'),
				},
				{
					value: '1',
					label: t('去会议室参加'),
				},
				{
					value: '3',
					label: t('电话参加'),
				},
			]
		}
	}
	/**切换入会方式 */
	const handleChangeMembershipMethod = async (v: string, meeting: MeetingEntity) => {
		if (v !== '') {
			let person_attend_info = {
				meetingMoid: meeting.meeting_id,
				isVideoMeeting: meeting.video,
				isParticipated: 1,
				participatedType: Number(v),
				participatedNO: '',
				reasonId: '',
			}
			update({
				attending_info: { ...person_attend_info },
			})
			const last_modify_time = meeting.last_modify_time ?? ''
			/**是否例会(审批列表中显示例会样式，其余以普通会议显示)*/
			const is_regular_meeting = meeting.isRegularMeeting
			/**当前用户参会情况（1-去会议室参加 2-通过个人客户端参加 3-电话参会） */
			const participated_type = meeting.current_user_attendee?.participated_type ?? 1
			/**是否是视频会议*/
			if (meeting.video) {
				if (v === '3') {
					setIsShowPhoneParticipateModal(true)
					update({ _option_meeting: meeting })
				} else {
					isValidLink({
						last_modify_time,
						meeting_moid: meeting.meeting_id,
						is_regular_meeting,
					})
				}
			} else {
				isValidLink({
					last_modify_time,
					meeting_moid: meeting.meeting_id,
					is_regular_meeting,
				})
			}
			if (v === '3') {
				setIsShowPhoneParticipateModal(true)
				update({ _option_meeting: meeting })
			}
		}
	}
	/**取消会议  时间确认框确认 */
	const actionCancelMeetingModalTimeConfirm = () => {
		if (checkboxCheckValueList.length > 0) {
			actionCancelMeetingModalTimeConfirmRest()
			setIsShowCancelModal(true) /**会议取消原因弹框显示 */
		}
	}
	/**取消会议  原因确认框确认 */
	const actionCancelMeetingModalReasonConfirm = async () => {
		const { regular_meeting_moid, meeting_id } = props.entity
		//首先判断取消会议 的原因  找到原因    然后根据是否是例会进行区分
		let _type = 0 /**1 是会议时间冲突   0 其他 */
		let _reason = ''
		if (cancel_value === 1) {
			_type = 1
			_reason = t('会议时间冲突')
		} else {
			if (cancel_resason.trim().length === 0) {
				let valid = await cancelResasonRef.current?.valid()
				if (!valid) return
			}
			_type = 0
			_reason = cancel_resason.trim()
		}
		let m = Message.loading(t('正在处理，请稍候……'))
		if (regular_meeting_moid == null || regular_meeting_moid == '' /**普通会议 */) {
			const res = await fetchDeleteMeetingByReason(meeting_id, { reason: _reason })
			if (res.success) {
				setIsShowCancelModal(false) /**会议取消原因弹框显示 */
				AjaxFetchAppointmentMeetingList()
				AjaxFetchNotParticipateMeetingList()
				m.hide()
			} else {
				failure(res.description || '')
				setIsShowCancelModal(false) /**会议取消原因弹框显示 */
				m.hide()
			}
		} else {
			//例会
			let default_id = init_select_checkbox_value
			let id_all: Array<string> = []
			date_info.forEach((item) => {
				if (checkboxCheckValueList.includes(item.value)) {
					id_all.push(item.meeting_moid || '')
				}
			})
			const res = await fetchDeleteRegularMeetingByReason(default_id, {
				meeting_moids: id_all.join(','),
				reason: _reason,
			})
			if (res.success) {
				setIsShowCancelModal(false) /**会议取消原因弹框显示 */
				AjaxFetchAppointmentMeetingList()
				AjaxFetchNotParticipateMeetingList()
				m.hide()
			} else {
				failure(res.description || '')
				setIsShowCancelModal(false) /**会议取消原因弹框显示 */
				m.hide()
			}
		}
	}
	/**取消会议Rest*/
	const actionCancelMeetingReset = () => {
		setCancelReason('')
	}
	const actionCancelMeeting = async (meeting: MeetingEntity) => {
		actionCancelMeetingReset()
		let day = meeting.start_time ? dayjs(meeting.start_time).format('YYYY-MM-DD') : '' /**获取年月日*/
		const { regular_meeting_moid } = meeting
		if (regular_meeting_moid != null && regular_meeting_moid != '') {
			const res = await fetchRegularMeeting(regular_meeting_moid)
			if (res.success) {
				const source = res.data
				const _source = []
				/**取消会议的时间的多选框*/
				const result = source.map((item, index) => {
					return {
						value: index + 1,
						label: item.day,
						height: 32.5,
						/**下面是接口数据 */
						meeting_moid: item.meeting_moid,
						day: item.day,
					}
				})
				_source.push(...result)
				setDateInfo(_source)
				/**获取初始化选中的值 */
				let _value_list: Array<number> = []
				_source.forEach((_item) => {
					if (_item.day === day) {
						_value_list.push(_item.value)
						setInitSelectCheckboxValue(_item.meeting_moid)
					}
				})
				setCheckboxCheckValueList(_value_list)
				setIsShowRegularMeeting(true) /**选择取消例会时间弹框关闭 */
			} else {
				failure(res.description || '')
			}
		} else {
			setIsShowCancelModal(true) /**会议取消原因弹框显示 */
		}
	}
	const actionStartNowMeeting = async (meeting: MeetingEntity) => {
		const { meeting_id, video, duration } = meeting
		if (video) {
			run(
				{
					create_type: 5,
					template_id: meeting_id,
					duration: duration,
				},
				(id) => {
					checkAuthentication(id, (success) => {
						if (success) {
							fetchSetCookie(
								{
									meeting_moid: meeting_id,
									type: 1,
								},
								function () {
									/**bug  此处跳转位置有问题*/
									window.location.href = MEETING_JUMP_URL + '/mcc/manager/' + meeting_id
								}
							)
						} else {
							jumpPage('meetingList')
						}
					})
				}
			)
		} else {
			/**非视频会议*/
			let m = Message.loading(t('正在处理，请稍候……'))
			const res = await fetchStartMeetingNow({ meetingMoid: meeting_id })
			if (res.success) {
				m.hide()
				jumpPage('meetingList')
			} else {
				failure(res.description || '')
			}
		}
	}
	/**参加会议重置*/
	const actionParticipateRest = () => {
		setPhone('')
		setParticipateTypeRadio(2)
	}
	const actionParticipate = (_meeting: MeetingEntity) => {
		actionParticipateRest()
		const { meeting_id, video, last_modify_time, isRegularMeeting } = _meeting
		/**是否例会(审批列表中显示例会样式，其余以普通会议显示)*/
		let person_attend_info = {
			isVideoMeeting: video,
			isParticipated: 1,
			participatedType: 1,
			meetingMoid: meeting_id,
			participatedNO: '',
			reasonId: '',
		}
		if (video) {
			update({
				attending_info: { ...person_attend_info } /**当前操作信息 */,
				_option_meeting: _meeting /**操作的会议*/,
			})

			if (SWITCH.meetingList.attendMethods) {
				setIsShowParticipateModal(true)
			} else {
				isValidLink({
					last_modify_time,
					meeting_moid: meeting_id,
					is_regular_meeting: isRegularMeeting,
				})
			}
		} else {
			isValidLink({
				last_modify_time,
				meeting_moid: meeting_id,
				is_regular_meeting: isRegularMeeting,
			})
		}
	}
	/**不参加会议重置*/
	const actionNotParticipateRest = () => {
		setNotParticipateReason('')
		setNotParticipateValue(1)
	}
	/**获取按钮组 */
	const getActionBtn = (meeting: MeetingEntity) => {
		const { is_attendee, current_user_attendee, is_cancel, is_now_start } = meeting
		const { is_participated } = current_user_attendee
		const _participate_flag = !!(is_attendee == 1 && is_participated == 0)
		const _not_participate_flag = !!(is_attendee == 1 && !(is_participated == 0))
		return (
			<>
				{!!is_now_start && (
					<Button
						className="btn"
						onClick={() => {
							const user = useGlobalStore.getState().user
							if (!user?.enable_meeting) {
								Alert(t('无会议管理权限，请通知管理员'))
								return false
							}
							actionStartNowMeeting(meeting)
						}}
					>
						{t('马上召开')}
					</Button>
				)}
				{!!is_cancel && (
					<Button
						className="btn"
						onClick={() => {
							const user = useGlobalStore.getState().user
							if (!user?.enable_meeting) {
								Alert(t('无会议管理权限，请通知管理员'))
								return false
							}
							actionCancelMeeting(meeting)
						}}
					>
						{t('取消会议', { context: 'SC1' })}
					</Button>
				)}
				{_participate_flag && (
					<Button
						className="btn"
						onClick={() => {
							const user = useGlobalStore.getState().user
							if (!user?.enable_meeting) {
								Alert(t('无会议管理权限，请通知管理员'))
								return false
							}
							actionParticipate(meeting)
						}}
					>
						{t('参加')}
					</Button>
				)}
				{_not_participate_flag && (
					<Button
						className="btn"
						onClick={() => {
							const user = useGlobalStore.getState().user
							if (!user?.enable_meeting) {
								Alert(t('无会议管理权限，请通知管理员'))
								return false
							}
							actionNotParticipateRest()
							setIsShowNotParticipateModal(true)
						}}
					>
						{t('不参加')}
					</Button>
				)}
			</>
		)
	}
	/**确定不参加*/
	const handleConfirmNotParticipate = async () => {
		const { meeting_id, video, last_modify_time } = props.entity
		let person_attend_info = {
			meetingMoid: meeting_id,
			isVideoMeeting: video,
			isParticipated: 0,
			participatedType: '',
			participatedNO: '',
			reasonId: '',
		}
		if (not_participate_value === 0) {
			if (not_participate_resason.trim().length === 0) {
				let valid = await notParticipateResasonRef.current?.valid()
				if (!valid) return
			}
			update({
				attending_info: { ...person_attend_info, ...{ reasonId: 0, reasonDesc: not_participate_resason } },
			})
		} else {
			update({
				attending_info: { ...person_attend_info, ...{ reasonId: 1, reasonDesc: t('会议时间冲突') } },
			})
		}
		/**是否例会(审批列表中显示例会样式，其余以普通会议显示)*/
		const is_regular_meeting = props.entity.isRegularMeeting
		isValidLink(
			{
				last_modify_time: last_modify_time,
				meeting_moid: meeting_id,
				is_regular_meeting: is_regular_meeting,
			},
			function () {
				setIsShowNotParticipateModal(false)
			}
		)
	}
	useEffect(() => {
		if (checkboxCheckValueList.length === date_info.length) {
			setAllValue(true)
		} else {
			setAllValue(false)
		}
	}, [checkboxCheckValueList, date_info])
	return (
		<>
			<Wrap className={props.className}>
				<CommonCard
					entity={props.entity}
					orderArr={props.orderArr}
					is_show_share={true}
					is_show_vcs={false}
					is_show_edit={!!props.entity.is_edit}
					is_show_e164={!!props.entity.video}
					is_show_domain_name={false}
					is_upload_file={true}
					file_num={props.entity.file_num ?? 0}
				></CommonCard>
				<WrapFooter className="meeting-card-footer">
					{!!SWITCH.meetingList.attendMethods && (
						<div className="attending_desc_or_option">
							{attendingMsg !== '' && <div className="attending_desc">{attendingMsg}</div>}
							{attendingMsg === '' && (
								<Select
									className="attending_option"
									options={getMembershipMethod(props.entity)}
									value={value}
									onClick={(e, v) => {
										const user = useGlobalStore.getState().user
										if (!user?.enable_meeting) {
											Alert(t('无会议管理权限，请通知管理员'))
											return false
										}
										handleChangeMembershipMethod(v, props.entity)
									}}
								/>
							)}
						</div>
					)}
					<div className="meeting_card_manager_option">{getActionBtn(props.entity)}</div>
				</WrapFooter>
			</Wrap>
			<AuthenticationCheck open={isAuthenticationOpen} setOpen={setIsAuthenticationOpen} callBack={successFn} />
			<Modal
				open={is_show_cancel_regular_meeting}
				title={t('取消会议')}
				width={400}
				height={260}
				onOk={() => {
					actionCancelMeetingModalTimeConfirm()
				}}
				onCancel={() => {
					setIsShowRegularMeeting(false)
				}}
				okText={t('确定')}
				cancelText={t('取消')}
			>
				<CheckBoxWrap>
					<CheckBox
						checked={allValue}
						height={32.5}
						onChange={(e, v) => {
							if (v) {
								let result = date_info.map((item) => item.value)
								setCheckboxCheckValueList(result)
							} else {
								setCheckboxCheckValueList([])
							}
						}}
					>
						{t('全部')}
					</CheckBox>
					<CheckBoxGroup
						options={date_info}
						direction="column"
						value={checkboxCheckValueList}
						onChange={(e, v, o, l) => {
							setCheckboxCheckValueList(v)
						}}
					/>
				</CheckBoxWrap>
			</Modal>
			{/*取消会议原因弹框*/}
			<Modal
				open={is_show_cancel_modal}
				title={t('取消会议')}
				width={400}
				height={260}
				onOk={() => {
					actionCancelMeetingModalReasonConfirm()
				}}
				onCancel={() => {
					setIsShowCancelModal(false)
				}}
				okText={t('确定')}
				cancelText={t('取消')}
			>
				<StyledRejectMeetingWrap>
					<div className="content">
						<div className="content_line">
							<Radio
								checked={cancel_value === 1}
								onChange={(e, v) => {
									setCancelValue(1)
								}}
								width={155}
								height={22}
							>
								{t('会议时间冲突')}
							</Radio>
						</div>
						<div className="content_line">
							<Radio
								checked={cancel_value === 0}
								onChange={(e, v) => {
									setCancelValue(0)
								}}
								width={105}
								height={22}
							>
								{t('其他')}
							</Radio>
							{cancel_value === 0 && (
								<Input
									className="input_msg"
									width={180}
									value={cancel_resason}
									placeholder=""
									focusMsg={t('请输入取消会议原因')}
									rule={{
										required: {
											showIcon: false,
											msg: t('取消会议原因不能为空'),
										},
									}}
									innerRef={cancelResasonRef}
									onChange={(e, v) => {
										setCancelReason(v)
									}}
								/>
							)}
						</div>
					</div>
				</StyledRejectMeetingWrap>
			</Modal>
			{/* 参加方式 */}
			<Modal
				open={is_show_participate_modal}
				title={t('参加会议')}
				width={400}
				height={260}
				okText={t('参加')}
				onOk={() => {
					if (participate_type_radio === 0) {
						Alert(t('请选择参会方式！'))
						return
					}
					if (participate_type_radio === 3) {
						setIsShowPhoneParticipateModal(true)
					} else {
						const { meeting_id, last_modify_time } = props.entity
						/**是否例会(审批列表中显示例会样式，其余以普通会议显示)*/
						const is_regular_meeting = props.entity.isRegularMeeting
						isValidLink({
							last_modify_time,
							meeting_moid: meeting_id,
							is_regular_meeting,
						})
					}
					setIsShowParticipateModal(false)
				}}
				onCancel={() => {
					setIsShowParticipateModal(false)
				}}
				cancelText={t('取消')}
			>
				<RadioWrap>
					<Radio
						checked={participate_type_radio === 2}
						onChange={(e, v) => {
							v && setParticipateTypeRadio(2)
						}}
						height={40}
						width={220}
					>
						{t('通过个人客户端参加')}
					</Radio>
					<Radio
						checked={participate_type_radio === 1}
						onChange={(e, v) => {
							v && setParticipateTypeRadio(1)
						}}
						height={40}
						width={220}
					>
						{t('去会议室参加')}
					</Radio>
					{props.entity.meeting_type !== 2 && (
						<Radio
							checked={participate_type_radio === 3}
							onChange={(e, v) => {
								v && setParticipateTypeRadio(3)
							}}
							height={40}
							width={220}
						>
							{t('电话参加')}
						</Radio>
					)}
				</RadioWrap>
			</Modal>
			{/* 参加方式(不参加会议弹框) */}
			<Modal
				open={is_show_not_participate_modal}
				title={t('不参加原因')}
				width={400}
				height={260}
				onOk={() => {
					handleConfirmNotParticipate()
				}}
				onCancel={() => {
					setIsShowNotParticipateModal(false)
				}}
				okText={t('确定')}
				cancelText={t('取消')}
			>
				<StyledRejectMeetingWrap>
					<div className="content">
						<div className="content_line">
							<Radio
								checked={not_participate_value === 1}
								onChange={(e, v) => {
									setNotParticipateValue(1)
								}}
								width={155}
								height={22}
							>
								{t('会议时间冲突')}
							</Radio>
						</div>
						<div className="content_line">
							<Radio
								checked={not_participate_value === 0}
								onChange={(e, v) => {
									setNotParticipateValue(0)
								}}
								width={105}
								height={22}
							>
								{t('其他')}
							</Radio>
							{not_participate_value === 0 && (
								<Input
									className="input_msg"
									width={180}
									value={not_participate_resason}
									placeholder=""
									focusMsg={t('请输入不参加会议的原因')}
									rule={{
										required: {
											showIcon: false,
											msg: t('不参加会议原因不能为空'),
										},
									}}
									innerRef={notParticipateResasonRef}
									onChange={(e, v) => {
										setNotParticipateReason(v)
									}}
								/>
							)}
						</div>
					</div>
				</StyledRejectMeetingWrap>
			</Modal>
			{/* 电话参加 */}
			<Modal
				open={is_show_phone_participate_modal}
				title={t('电话号码')}
				width={400}
				height={260}
				onOk={async () => {
					let valid = await ref.current?.valid()
					if (!valid) return
					if (attending_info) {
						update({
							attending_info: {
								...attending_info,
								...{ participatedNO: phone, participatedType: 3 },
							},
						})
						const { meeting_id, last_modify_time } = props.entity
						/**是否例会(审批列表中显示例会样式，其余以普通会议显示)*/
						const is_regular_meeting = props.entity.isRegularMeeting
						isValidLink(
							{
								last_modify_time,
								meeting_moid: meeting_id,
								is_regular_meeting,
							},
							() => {
								setPhone('')
								setIsShowPhoneParticipateModal(false)
							}
						)
					}
				}}
				onCancel={() => {
					setIsShowPhoneParticipateModal(false)
				}}
				okText={t('确定')}
				cancelText={t('取消')}
			>
				<PhoneModalWrap>
					<div className="content">
						<Input
							width={280}
							value={phone}
							height={31}
							placeholder=""
							focusMsg=""
							innerRef={ref}
							rule={{
								required: {
									showIcon: false,
									msg: t('电话号码不能为空，请输入'),
								},
								regular: [
									{
										regex: regexEnum.phoneIllegal,
										msg: t('存在非法字符，请重新输入'),
									},
									{
										regex: regexEnum.phoneMaxLength,
										msg: t('最多20个字符，包括 数字 . _ - * # 空格'),
									},
								],
							}}
							onChange={(e, v) => {
								setPhone(v)
							}}
						/>
					</div>
				</PhoneModalWrap>
			</Modal>
		</>
	)
}
